package com.base.commonlib.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.base.commonlib.http.utils.SnackBarUtil;

import java.util.ArrayList;

/**
 * Created by jp on 2018/8/2.
 */

public class PermissionCheckUtil {
    public static void checkAndRequest(Activity activity, String[] permissions, OnPermissionRequestSuccess listener) {
        ArrayList<String> notGrantedPs = new ArrayList<>();
        if (permissions == null || permissions.length <= 0) {
            return;
        }
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                notGrantedPs.add(permission);
            }
        }

        if (notGrantedPs.size() > 0) {
            ActivityCompat.requestPermissions(activity, notGrantedPs.toArray(new String[notGrantedPs.size()]), 0);
        }else
        {
            if(listener!=null)
            {
                listener.onPermissionSuccess();
            }
        }

    }


    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, final Activity activity, View v)
    {
        for(Integer code:grantResults)
        {
            if(code!=0)
            {
                SnackBarUtil.showMsg_Action_miss(v, "缺少相应权限!", "去设置", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                        intent.setData(uri);
                        activity.startActivity(intent);
                    }
                });
                return;
            }
        }
        ((OnPermissionRequestSuccess)activity).onPermissionSuccess();


    }

    public interface OnPermissionRequestSuccess
    {
        void onPermissionSuccess();
    }
}
